package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.service.UserService;
import com.jt.pojo.User;
import com.jt.service.DubboUserService;
import com.jt.util.CookieUtil;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Reference(check = false)
    private DubboUserService dubboUserService;
    @Autowired
    private JedisCluster jedisCluster;
    @RequestMapping("/{modelName}")
    public String model(@PathVariable String modelName){
        return modelName;
    }
    @RequestMapping("findUserList")
    @ResponseBody
    public List<User> findUserList(){
        return userService.findUserList();
    }
    /*/user/doLogin?r=*/

    @RequestMapping("/doRegister")
    @ResponseBody
    public SysResult doRegister(User user){
        if (!(StringUtils.hasLength(user.getUsername())&&StringUtils.hasLength(user.getPassword()))){
            return SysResult.fail();
        }
        dubboUserService.doRegister(user);
        return SysResult.success();
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public SysResult doLogin(User user, HttpServletResponse response){
       String ticket=dubboUserService.doLogin(user);
       if (!StringUtils.hasLength(ticket)){
           return SysResult.fail();
       }
       CookieUtil.addCookie(response, "JT_TICKET", ticket, "jt.com", 7*24*60*60);
       return SysResult.success();
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        String ticket= CookieUtil.getCookieValue(request, "JT_TICKET");
        if (StringUtils.hasLength(ticket)){
            jedisCluster.del(ticket);
            CookieUtil.addCookie(response,"JT_TICKET","","jt.com",0);
        }
        return "redirect:/";
    }
}
